package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.HashMap;
import java.util.Map;

/**
 * <a href="https://leetcode.cn/problems/majority-element/description/?envType=study-plan-v2&envId=top-100-liked">169. 多数元素</a>
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode097 {
    public static void main(String[] args) {
        HotCode097 hotCode = new HotCode097();
        int[] nums = {2,2,4,4,4};
        System.out.println(hotCode.majorityElement(nums));
    }

    public int majorityElement(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        int half = nums.length >> 1;
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
            if (map.get(num) > half) {
                return num;
            }
        }
        throw new RuntimeException("给定数组中没有出现过多数元素");
    }
}